//
//  HomePingJiaVC.m
//  QoilPublic
//
//  Created by SunChao on 2018/3/1.
//  Copyright © 2018年 孙超. All rights reserved.
//

#import "HomePingJiaVC.h"
#import "GlobalStarCell.h"
#import "DetailStarCell.h"
#import "MarkCell.h"
#import "AnonymousCell.h"
#import "PingJiaSuccessVC.h"
#import "EvaluateTextCell.h"
@interface HomePingJiaVC ()<UITableViewDelegate,UITableViewDataSource,StarSelectedDelegate,AdviseTextDelegate>
{
    NSString *_star1;
    NSString *_star2;
    NSString *_star3;
    NSString *_adviseString;
    NSArray *_textArr;
    NSArray *_markArray;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)UIButton *judgeButton;
@property (nonatomic,strong)NSArray *orderArray;
@property (nonatomic,copy)NSString *orderId;
@property (nonatomic,strong)NSString *scoreOrder;
@end

@implementation HomePingJiaVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"总体评价";
    
    UIBarButtonItem *leftButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain
                                                                      target:self action:@selector(OnLeftButton:)];
    [leftButtonItem setImage:[UIImage imageNamed:@"X"]];
    self.navigationItem.leftBarButtonItem = leftButtonItem;
    
   
    [self gainOrderInfo];
}

- (void)gainOrderInfo{
    
    NSString *url = [QParamService urlWithAction:@"order/findUserOrderEvaluate"];
    NSDictionary *params = [QParamService GainStarText];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        if(error){
            
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
           
            self.orderArray = basModel.items;
            
            if (self.orderArray.count>0) {
                
                self.orderId = [[self.orderArray objectAtIndex:0] objectForKey:@"orderId"];
                self.scoreOrder = [[self.orderArray objectAtIndex:0]objectForKey:@"targetAmount"];
            }
            
        }else{
            
        }
         [self createTableView];
    }];
}

- (void)OnLeftButton:(id)sender {
    NSString *title = NSLocalizedString(@"放弃评价", nil);
    NSString *message = NSLocalizedString(@"", nil);
    NSString *cancelButtonTitle = NSLocalizedString(@"残忍退出", nil);
    NSString *otherButtonTitle = NSLocalizedString(@"继续评价", nil);
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's cancel action occured.");
        [[NSNotificationCenter defaultCenter]postNotificationName:@"HomePingJiaNotification" object:nil];
        
    }];
    [cancelAction setValue:[UIColor lightGrayColor] forKey:@"_titleTextColor"];
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"The \"Okay/Cancel\" alert's other action occured.");
    }];
    [otherAction setValue:[UIColor redColor] forKey:@"_titleTextColor"];

    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];

}



-(void)createTableView{
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStyleGrouped];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    [_tableView registerNib:[UINib nibWithNibName:@"DetailStarCell" bundle:nil] forCellReuseIdentifier:@"DetailStarCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"MarkCell" bundle:nil] forCellReuseIdentifier:@"MarkCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"EvaluateTextCell" bundle:nil]forCellReuseIdentifier:@"EvaluateTextCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"AnonymousCell" bundle:nil] forCellReuseIdentifier:@"AnonymousCell"];
    
    NSString *score =[NSString stringWithFormat:@"%d", [self.scoreOrder intValue]];
    NSString *str = [NSString stringWithFormat:@"提交评价即可获得%@积分",score];
    NSMutableAttributedString *tmpStr = [[NSMutableAttributedString alloc] initWithString:str];
    NSRange range1 = [[tmpStr string]rangeOfString:str];
    NSRange range2 = [[tmpStr string]rangeOfString:score];
    [tmpStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial-BoldItalicMT" size:16.0] range:range1];
    [tmpStr addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:range1];
    [tmpStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:255.0/255.0 green:209.0/255.0 blue:51.0/255.0 alpha:1.0f]range:range2];

    _judgeButton = [UIButton buttonWithType:0];
    _judgeButton.frame = CGRectMake(0, kScreenHeight-50, kScreenWidth, 50);
    [_judgeButton setBackgroundColor:[UIColor colorWithRed:37.0/255.0 green:156.0/255.0 blue:210.0/255.0 alpha:1.0f]];
   [_judgeButton setAttributedTitle:tmpStr forState:UIControlStateNormal];
    [_judgeButton addTarget:self action:@selector(judgeButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_judgeButton];
}

#pragma mark--提交评价
- (void)judgeButtonAction{
    
    
    NSString *url = [QParamService urlWithAction:@"order/saveEvaluateOrder"];

    if (_star1 == nil || [_star1 isEqualToString:@""]) {
        _star1 = @"5";
    }
    if (_star2 == nil || [_star2 isEqualToString:@""]) {
        _star2 = @"5";
    }
    if (_star3 == nil || [_star3 isEqualToString:@""]) {
        _star3 = @"5";
    }

    NSArray *dic =  @[
                      @{
                          @"id" : @"1",
                          @"name" : @"服务态度",
                          @"stars" : _star1
                          },
                      @{
                          @"id" : @"2",
                          @"name" : @"配送速度",
                          @"stars" : _star2
                          },
                      @{
                          @"id" : @"3",
                          @"name" : @"油品质量",
                          @"stars" : _star3
                          }
                      ];
    NSData *data=[NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"jsonStr==%@",jsonStr);
    NSString *markString = [_markArray componentsJoinedByString:@";"];
    
    
    NSLog(@"markSting = %@",markString);
    NSDictionary *params = [QParamService CommentOrder:[[self.orderArray objectAtIndex:0]objectForKey:@"orderId"] content:markString evalJsonstr:jsonStr];

    [QViewUtility showMBHudToView:self.view hideBg:NO];

    [[QHttpManager sharedManager] POST:url parameterMD5:params completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        [QViewUtility hideMBHudToView:self.view];
        if(error){
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            if (self.orderArray.count>1) {
                HomePingJiaVC *vc = [[HomePingJiaVC alloc]init];
                
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
                [self presentViewController:nav animated:YES completion:nil];
            }
            if (self.orderArray.count == 1) {
             
                PingJiaSuccessVC *vc =  [[PingJiaSuccessVC alloc]init];
                vc.orderId = [[self.orderArray objectAtIndex:0] objectForKey:@"orderId"];
                [self presentViewController:vc animated:YES completion:nil];
           
            }
           

        }else{
            [QViewUtility showAlertViewWithImage:[UIImage imageNamed:@"cry_image"] content:basModel.errMsg btnTitle:showAlertBtnTitle type:1 myBlock:^{}];
        }
    }];
}

#pragma mark --- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    
    if (section == 0) {
        return 3;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    __weak HomePingJiaVC *wSelf = self;
    
    if (indexPath.section == 0) {
        NSArray *arr = [NSArray new];

        arr = @[@"服务态度",@"配送速度",@"油品质量"];
        DetailStarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailStarCell"];
        if (arr.count>0) {
            NSString *str  = [arr objectAtIndex:indexPath.row];
            [cell SetupStarViewWith:str indexPathOfRow:indexPath.row canEdit:YES starNum:@"" evaluate:@""];
        }
        
        cell.delegate = self;
        cell.tag = indexPath.row + 1;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
    if (indexPath.section == 1) {
        MarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MarkCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.block = ^(NSArray *array){
            __strong HomePingJiaVC *sSelf = wSelf;
            sSelf->_markArray = array;
            
        };
        return cell;
    }
    if (indexPath.section == 2) {
        
        EvaluateTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluateTextCell"];
        cell.delegate = self;
        return cell;
    }
    if (indexPath.section == 3) {
        AnonymousCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AnonymousCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        
        return 50;
    }
    if (indexPath.section == 1) {
        
        return 100;
    }
    if (indexPath.section == 2) {
        
        return 200;
    }
    if (indexPath.section == 3) {
        return 60;
    }
    return 0;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 8;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return [[UIView alloc]init];
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}
//字典转json格式字符串：
- (NSString*)dictionaryToJson:(id)dic
{
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


- (void)gainStarWithText: (NSString *) text indexPathOfRow:(NSUInteger )row{
    if (row == 0) {
        _star1 = text;
    }
    if (row == 1) {
        _star2 = text;
    }
    if (row == 2) {
        _star3 = text;
    }
}
-(void)gainStarWithText:(NSString *)text{
    
    _adviseString = text;
}

@end 
